package com.service;

import com.alibaba.fastjson.JSONArray;
import com.dao.InputProgrameDAO;
import com.dao.ProgrameTypeDAO;
import com.pojo.InputPrograme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class InputProgrameService {

     @Autowired
     private InputProgrameDAO inputProgrameDAO;



     /**
      * 查所有输入节目表
      * @return
      */
     public List getAll()
     {
          return inputProgrameDAO.findAll(Sort.by("orders"));
     }

     /**
      * 批量移动
      * @param data
      * @param direction
      */
     public List batchMove(String data, String direction) {
          List<InputPrograme> list = JSONArray.parseArray(data, InputPrograme.class);
          switch (direction)
          {
               case "up":
                    for (InputPrograme p:list)
                    {
                        InputPrograme tempP = inputProgrameDAO.getOne(p.getId());
                       int currSort = tempP.getOrders();//当前序列
                       int prev     = currSort-1;//上一个序列
                       if (prev==0)
                       {
                            break;
                       }
                       //根据序列号查找对象
                       InputPrograme prevInputPrograme = inputProgrameDAO.findInputProgrameByOrders(prev);
                       //上一个存当前序列
                       prevInputPrograme.setOrders(currSort);
                       //当前存上一个序号
                       p.setOrders(prev);

                       //保存
                       inputProgrameDAO.save(p);
                       inputProgrameDAO.save(prevInputPrograme);
                    }
                    break;

               case "down":
                    Collections.reverse(list);//倒序
                    for (InputPrograme p:list)
                    {
                        InputPrograme tempP = inputProgrameDAO.getOne(p.getId());
                        int currSort = tempP.getOrders();//当前序列
                         int nextSort     = currSort+1;//下一个序列
                        /* if (prev==0)
                         {
                              break;
                         }*/
                         //根据序列号查找对象
                         InputPrograme nextInputPrograme = inputProgrameDAO.findInputProgrameByOrders(nextSort);
                         //上一个存当前序列
                         nextInputPrograme.setOrders(currSort);
                         //当前存下一个序号
                         p.setOrders(nextSort);

                         //保存
                         inputProgrameDAO.save(p);
                         inputProgrameDAO.save(nextInputPrograme);
                    }
                   Collections.reverse(list);//倒序
                    break;
          }
         System.out.println(list);
         return list;
     }
}
